const Base = require('./base.js');
module.exports = class extends Base {
  __before() {
    this.paymentService = think.rpc.payment.payment;
    this.informationService = think.rpc.information.information;
  }
  // 微信支付回调
  async wxnotifyAction() {
    const notifyObj = this.post('xml');
    if (think.isEmpty(notifyObj)) {
      return this.payFail('参数不对');
    }
    const result = {};
    for (const key of Object.keys(notifyObj)) {
      result[key] = notifyObj[key][0];
    }
    if (result.return_code !== 'SUCCESS') {
      return this.payFail(result.return_msg);
    }
    think.logger.info('wxnotify result:', result);
    const outTradeNo = result.out_trade_no;
    if (result.result_code !== 'SUCCESS') {
      return this.payFail(result.err_code_des, outTradeNo);
    }
    const rt = await this.paymentService.verifyPaymentSign(result);
    if (!rt) {
      return this.payFail('签名错误', outTradeNo);
    }
    try {
      const paymentRow = await this.paymentService.queryByOutTradeNo(outTradeNo, 'id,business_id,business_type,amount');
      if (think.isEmpty(paymentRow)) {
        return this.payFail('订单不存在', outTradeNo);
      }
      if (paymentRow.amount !== parseInt(result.total_fee)) {
        return this.payFail('金额不一致', outTradeNo + ',paymentRow.amount:' + paymentRow.amount + '->' + result.total_fee);
      }
      // 支付成功
      if (await this.paymentService.paySuccess(paymentRow.id, {transactionId: result.transaction_id}) === 0) {
        return this.paySuccess();
      }
      await this.informationService.paySuccess(paymentRow.business_id, paymentRow.id);
      think.logger.info('微信支付回调支付成功,wxnotify:', outTradeNo);
      return this.paySuccess();
    } catch (e) {
      think.logger.error('微信支付回调,wxnotify:', e);
      return this.payFail('订单不存在', outTradeNo);
    }
  }
  payFail(msg, outTradeNo) {
    if (outTradeNo) {
      think.logger.error('微信支付回调失败,wxnotify fail,', msg, ',out_trade_no,', outTradeNo);
    } else {
      think.logger.error('微信支付回调失败,wxnotify fail,', msg);
    }
    return `<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[${msg}]]></return_msg></xml>`;
  }
  paySuccess() {
    return `<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`;
  }
};
